<?php
//collection of short helper functions, on which some classes are strongly depending

function UTILS_in_array($arr_haystack, $needle){
	foreach($arr_haystack as $key=>$token){
		if ($token == $needle){
			return true;
		}
	}
	return false;
}

function UTILS_size_convert($size){
    $unit=array('b','kb','mb','gb','tb','pb');
    return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}

//Начало помойки

function UTIL_create_structure($dir, $mode = 0777, $recursive = true) {
	if( is_null($dir) || $dir === "" ){
		return false;
	}

	if( is_dir($dir) || $dir === "/" ){
		return true;
	}
	if( UTIL_create_structure(dirname($dir), $mode, $recursive) ){
		return mkdir($dir, $mode);
	}
	return false;
}


//TODO: rewrite me using SPL
function UTIL_copy_recursive($source, $dest, $options=array('folderPermission'=>0777,'filePermission'=>0777), $cb)
{
	$result=false;

	//For Cross Platform Compatibility
	if (!isset($options['noTheFirstRun'])) {
		$source=str_replace('\\','/',$source);
		$dest=str_replace('\\','/',$dest);
		$options['noTheFirstRun']=true;
	}

	if (is_file($source)) {
		if ($dest[strlen($dest)-1]=='/') {
					if (!file_exists($dest)) {
						UTIL_create_structure($dest,$options['folderPermission'],true);
					}
					$__dest=$dest."/".basename($source);
				} else {
					$__dest=$dest;
				}

				$result=copy($source, $__dest);
				if (is_callable($cb)){
					call_user_func_array($cb,array($__dest));
				}

				chmod($__dest,$options['filePermission']);

		} elseif(is_dir($source)) {
			if ($dest[strlen($dest)-1]=='/') {
				if ($source[strlen($source)-1]=='/') {
					//Copy only contents
				} else {
					//Change parent itself and its contents
					$dest=$dest.basename($source);
					@mkdir($dest);
					chmod($dest,$options['filePermission']);
				}
			} else {
		if ($source[strlen($source)-1]=='/') {
			//Copy parent directory with new name and all its content
			@mkdir($dest,$options['folderPermission']);
				chmod($dest,$options['filePermission']);
			} else {
				//Copy parent directory with new name and all its content
				@mkdir($dest,$options['folderPermission']);
				chmod($dest,$options['filePermission']);
				}
		}

		$dirHandle=opendir($source);
		while($file=readdir($dirHandle))
		{
			if($file!="." && $file!=".." && $file!=".svn"){
				$__dest=$dest."/".$file;
				$__source=$source."/".$file;

				if ($__source!=$dest) {
					$result=UTIL_copy_recursive($__source, $__dest, $options, $cb);
				}
			}
		}
		closedir($dirHandle);

	} else {
		$result=false;
	}
	return $result;
}


//Конец помойки


?>
